﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Account;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Model.DbModels.Finance;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Model.ViewModels.Account;
using TomNet.IMSC.Web.Filters;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.Account.Controllers
{
    [Description("财务-出款单")]
    [GlobalAuthorization]
    public class OutMoneyOrdersController : BaseController
    {
        /// <summary>
        /// 出款单
        /// </summary>
        public IOutMoneyOrdersContract OMOContract { get; set; }
        /// <summary>
        /// 出款单明细
        /// </summary>
        public IOutMoneyOrdersRunningsContract OMORContract { get; set; }
        /// <summary>
        /// 出款帐户
        /// </summary>
        public IOutMoneyAccountContract OMAContract { get; set; }
        /// <summary>
        /// 代理
        /// </summary>
        public IAgentContract AContract { get; set; }
        /// <summary>
        /// 佣金流水
        /// </summary>
        public IBrokerageRunningsContract BContract { set; get; }// 佣金流水
        /// <summary>
        /// 管理员
        /// </summary>
        public IStaffContract SContract { get; set; }
        /// <summary>
        /// 新房明细
        /// </summary>
        public INewHouseRunningsContract NHContract { get; set; }
        /// <summary>
        /// 低价房明细
        /// </summary>
        public ILowPriceHouseRunningsContract LPHContract { get; set; }
        /// <summary>
        /// 装修明细
        /// </summary>
        public IDecorationRunningsContract DContract { get; set; }
        /// <summary>
        /// 金融明细
        /// </summary>
        public IFinanceRunningsContract FContract { get; set; }
        /// <summary>
        /// 佣金结算明细
        /// </summary>
        public IBrokerageSettleAccountsRunningsContract BSContract { get; set; }
        /// <summary>
        /// 新房佣金提点等级
        /// </summary>
        public IBuildingsBrokerageLevelContract BBLContract { get; set; }
        /// <summary>
        /// 装修佣金提点等级
        /// </summary>
        public IDecorationCompanyBrokerageLevelContract DBLContract { get; set; }
        /// <summary>
        /// 佣金明细
        /// </summary>
        public IBrokerageRunningsContract BRContract { get; set; }
        public IBrokerageTypeContract BTContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        [Description("财务-出款单列表面页")]
        public ActionResult OutMoneyOrdersList(int ModuleID)
        {
            ViewBag.ModuleID = ModuleID;
            return View();
        }
        [Description("财务-获得出款单列表数据")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersListAsync(int pageIndex, int pageSize, int ModuleID)//, string search = "", int depid
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var query = from a in OMOContract.Entities
                        join b in AContract.Entities on a.AgentID equals b.Id
                        select new
                        {
                            OrderNumber = a.OrderNumber,
                            State = a.State,
                            CreateTime = a.CreatedTime,
                            AgentName = b.Name,
                            ModuleID=a.ModuleID,
                            AgentID=a.AgentID,
                            ID=a.Id,
                        };
            query = query.Where(p => p.ModuleID == ModuleID);
            if (model.AgentId > 0)
            {
                query = query.Where(p => p.AgentID == model.AgentId);
            }
            //if (State > 0)// 状态  1生成中    2财务审核中    3渠道审核中    4管理审核中   5出款中   6核算中   7已完成
            //{
            //    query = query.Where(p => p.State == State);
            //}

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreateTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : null;

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("财务-添加出款单列表面页")]
        public ActionResult AddOutMoneyOrders(int ModuleID)
        {
            ViewBag.ModuleID = ModuleID;
            return View();
        }
        [Description("财务-添加出款单")]
        [HttpPost, AjaxOnly]
        public ActionResult AddOutMoneyOrdersAsync(OutMoneyOrders entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            string OrderNumber = entity.CreatedTime.ToString("yyyyMMdd");
            try
            {
                if (OMOContract.Entities.Count(p => p.AgentID == model.AgentId && p.ModuleID == entity.ModuleID && p.OrderNumber == OrderNumber) > 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "每天只能添加一个出款单";
                }
                else
                {
                    entity.OrderNumber = OrderNumber;
                    entity.State = 1;
                    entity.AgentID = model.AgentId;
                    entity.CreatedTime = DateTime.Now;
                    var count = OMOContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("财务-出款单明细列表面页")]
        public ActionResult OutMoneyOrdersRunningsList(int ID)
        {
            ViewBag.ID = ID;
            ViewBag.OrderState = OMOContract.GetByKey(ID).State;
            ViewBag.ModuleID = OMOContract.GetByKey(ID).ModuleID;
            return View();
        }
        [Description("财务-获得出款单明细列表数据")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersRunningsListAsync(int pageIndex, int pageSize, int ID)//, string search = "", int depid
        {
            IQueryable<OutMoneyOrdersRunningsListModel> query = Enumerable.Empty<OutMoneyOrdersRunningsListModel>().AsQueryable();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var om = OMOContract.GetByKey(ID);
            switch (om.ModuleID)
            {
                case 1:
                    query = from a in OMORContract.Entities
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id
                            join c in BRContract.Entities on a.BrokerageRunningsID equals c.Id
                            join d in NHContract.Entities on c.RunningsID equals d.Id
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount=c.Amount,
                                BrokerageTax=c.Tax,
                                BrokerageSettledAmount= (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.BuildingName,
                                ItemPrice = d.TotalPrice,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState,a.FinanceRemark,a.OriginState,a.OriginRemark,a.SysState,a.SysRemark,a.OutMoneyState,a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                ItemTag=d.Address,
                                ItemTime=d.SubscribeTime,
                                SellStaffID=d.SellStaffID,
                                SellStaffName=eu6d.Name
                            };
                    break;
                case 2:
                case 3:
                    query = from a in OMORContract.Entities
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id
                            join c in BRContract.Entities on a.BrokerageRunningsID equals c.Id
                            join d in LPHContract.Entities on c.RunningsID equals d.Id
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount = c.Amount,
                                BrokerageTax = c.Tax,
                                BrokerageSettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.BuildingName,
                                ItemPrice = d.LowPrice,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState, a.FinanceRemark, a.OriginState, a.OriginRemark, a.SysState, a.SysRemark, a.OutMoneyState, a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                ItemTag=d.HouseNumber,
                                ItemTime=d.SubscribeTime,
                                SellStaffID=d.SellStaffID,
                                SellStaffName=eu6d.Name
                            };
                    break;
                case 4:
                    query = from a in OMORContract.Entities
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id
                            join c in BRContract.Entities on a.BrokerageRunningsID equals c.Id
                            join d in DContract.Entities on c.RunningsID equals d.Id
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount = c.Amount,
                                BrokerageTax = c.Tax,
                                BrokerageSettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.DecorationCompanyName,
                                ItemPrice = d.TotalPrice,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState, a.FinanceRemark, a.OriginState, a.OriginRemark, a.SysState, a.SysRemark, a.OutMoneyState, a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                ItemTag=d.CustomerAddress,
                                ItemTime=d.SubscribeTime,
                                SellStaffID=d.SellStaffID,
                                SellStaffName=eu6d.Name
                            };
                    break;
                default:
                    break;
            }
            //query = query.Where(p => p.ModuleID == ModuleID);
            //if (model.AgentId > 0)
            //{
            //    query = query.Where(p => p.AgentID == model.AgentId);
            //}
            //if (State > 0)// 状态  1生成中    2财务审核中    3渠道审核中    4管理审核中   5出款中   6核算中   7已完成
            //{
            //    query = query.Where(p => p.State == State);
            //}

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.ID);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : null;

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("财务-添加出款单明细面页")]
        public ActionResult AddOutMoneyOrdersRunnings(int ModuleID, string BrokerageRunningsIDs)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.BrokerageRunningsIDs = BrokerageRunningsIDs;
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var query = OMOContract.Entities.Where(p => p.ModuleID == ModuleID && p.AgentID == model.AgentId && p.State == 1).OrderByDescending(p => p.CreatedTime).ToList();
            System.Text.StringBuilder ol = new System.Text.StringBuilder();
            foreach (var item in query)
            {
                ol.Append(@"<option value=""" + item.Id + @""">" + item.OrderNumber + "</option>");
            }
            ViewBag.OutMoneyOrdersList = ol.ToString();
            return View();
        }

        [Description("财务-添加出款单明细")]
        [HttpPost, AjaxOnly]
        public ActionResult AddOutMoneyOrdersRunningsAsync(int OutMoneyOrdersID,string BrokerageRunningsIDs,int AccountType,decimal OutRate)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            string[] ids = BrokerageRunningsIDs.Split(',');
            try
            {
                if (OMOContract.Entities.Count(p => p.Id == OutMoneyOrdersID && p.State == 1) == 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "该出款单已封单。";
                }
                else
                {
                    OMORContract.Repository.UnitOfWork.BeginTransaction();
                    foreach (var item in ids)
                    {
                        OutMoneyOrdersRunnings m = new OutMoneyOrdersRunnings();
                        BrokerageRunnings brm = BContract.GetByKey(Convert.ToInt32(item));
                        NewHouseRunnings nrm;
                        LowPriceHouseRunnings lprm;
                        DecorationRunnings drm;
                        FinanceRunnings frm;
                        int IntermediaryID = 0;
                        int OriginStaffID = 0;
                        switch (brm.ModuleID)
                        {
                            case 1:
                                nrm = NHContract.GetByKey(brm.RunningsID);
                                IntermediaryID = nrm.IntermediaryID;
                                OriginStaffID = nrm.OriginStaffID;
                                break;
                            case 2:
                            case 3:
                                lprm = LPHContract.GetByKey(brm.RunningsID);
                                IntermediaryID = lprm.IntermediaryID;
                                OriginStaffID = lprm.OriginStaffID;
                                break;
                            case 4:
                                drm = DContract.GetByKey(brm.RunningsID);
                                IntermediaryID = drm.IntermediaryID;
                                OriginStaffID = drm.OriginStaffID;
                                break;
                            default:
                                break;
                        }
                        Intermediary im = IntermediaryContract.GetByKey(IntermediaryID);
                        if (OMORContract.Entities.Count(p=>p.BrokerageRunningsID==brm.Id && p.OutMoneyOrdersID==OutMoneyOrdersID)>0)
                        {
                            continue;
                        }
                        if (AccountType==1)
                        {
                            m.AccountBank = im.PublicAccountBank;
                            m.AccountName = im.PublicAccountUserName;
                            m.AccountNumber = im.PublicAccountNumber;
                        }
                        else
                        {
                            m.AccountBank = im.PrivateAccountBank;
                            m.AccountName = im.PrivateAccountUserName;
                            m.AccountNumber = im.PrivateAccountNumber;
                        }
                        if (BSContract.Entities.Count(p=>p.BrokerageRunningsID==brm.Id)==0)
                        {
                            m.Amount = brm.Amount - brm.Tax;
                        }
                        else
                        {
                            m.Amount = brm.Amount - brm.Tax - BSContract.Entities.Where(p => p.BrokerageRunningsID == brm.Id).Sum(p => p.Amount);
                        }
                        m.Amount = m.Amount * OutRate;
                        m.BrokerageRunningsID = brm.Id;
                        m.CreateStaffID = model.Id;
                        m.CreateTime = DateTime.Now;
                        m.FinanceRemark = "";
                        m.FinanceStaffID = 0;
                        m.FinanceState = 0;
                        m.FinanceTime = DateTime.Now;
                        m.OriginRemark = "";
                        m.OriginStaffID = OriginStaffID;
                        m.OriginState = 0;
                        m.OriginTime = DateTime.Now;
                        m.OutMoneyAccountID = 0;
                        m.OutMoneyOrdersID = OutMoneyOrdersID;
                        m.OutMoneyRemark = "";
                        m.OutMoneyStaffID = 0;
                        m.OutMoneyState = 0;
                        m.OutMoneyTime = DateTime.Now;
                        m.SysRemark = "";
                        m.SysStaffID = 0;
                        m.SysState = 0;
                        m.SysTime = DateTime.Now;
                        if (m.Amount<=0)
                        {
                            continue;
                        }
                        OMORContract.Insert(m);
                    }
                    OMORContract.Repository.UnitOfWork.Commit();
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
                OMORContract.Repository.UnitOfWork.Rollback();
            }
            return JsonEx(result);
        }


        [Description("财务-出款单进入审核流程")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersNextAsync(int OutMoneyOrdersID)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                if (OMOContract.Entities.Count(p => p.Id == OutMoneyOrdersID && p.State == 1) == 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
                else
                {
                    var m = OMOContract.GetByKey(OutMoneyOrdersID);
                    m.State = 2;
                    var count = OMOContract.Update(m);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "操作操作";
            }
            return JsonEx(result);
        }

        [Description("财务-出款单审核面页")]
        public ActionResult OutMoneyOrdersAuditing(int ID,string IDs)
        {
            ViewBag.ID = ID;
            ViewBag.IDs = IDs;
            return View();
        }
        [Description("财务-出款单审核")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersAuditingAsync(int OutMoneyOrdersID,int State ,string Remark,string IDs)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var omo = OMOContract.GetByKey(OutMoneyOrdersID);
            try
            {
                int count = 0;
                string[] ids = IDs.Split(',');
                switch (omo.State)
                {
                    case 2://财务审核
                        count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.FinanceState == 0 && ids.Contains(p.Id.ToString()), p => new OutMoneyOrdersRunnings { FinanceState = State, FinanceRemark = Remark, FinanceStaffID = model.Id, FinanceTime = DateTime.Now });
                        if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.FinanceState == 0) == 0)
                        {
                            OMOContract.UpdateDirect(p => p.Id == OutMoneyOrdersID, p => new OutMoneyOrders { State = 3 });
                        }
                        break;
                    case 3://渠道审核
                        count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.OriginState == 0 && p.FinanceState == 1 && ids.Contains(p.Id.ToString()) && p.OriginStaffID == model.Id, p => new OutMoneyOrdersRunnings { OriginState = State, OriginRemark = Remark, OriginTime = DateTime.Now });
                        if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.OriginState == 0 && p.FinanceState == 1) == 0)
                        {
                            OMOContract.UpdateDirect(p => p.Id == OutMoneyOrdersID, p => new OutMoneyOrders { State = 4 });
                        }
                        break;
                    case 4://管理审核
                        count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.SysState == 0 && p.FinanceState == 1 && p.OriginState == 1 && ids.Contains(p.Id.ToString()), p => new OutMoneyOrdersRunnings { SysState = State, SysRemark = Remark, SysStaffID = model.Id, SysTime = DateTime.Now });
                        if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.SysState == 0 && p.FinanceState == 1 && p.OriginState == 1) == 0)
                        {
                            OMOContract.UpdateDirect(p => p.Id == OutMoneyOrdersID, p => new OutMoneyOrders { State = 5 });
                        }
                        break;
                    default:
                        break;
                }
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "操作失败";
            }
            return JsonEx(result);
        }
        [Description("财务-出款单出款面页")]
        public ActionResult OutMoneyOrdersOutMoney(int ID, string IDs)
        {
            ViewBag.ID = ID;
            ViewBag.IDs = IDs;
            return View();
        }
        [Description("财务-出款单出款")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersOutMoneyAsync(int OutMoneyOrdersID,int State ,string Remark,string IDs,int OutMoneyAccountID)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var omo = OMOContract.GetByKey(OutMoneyOrdersID);
            try
            {
                int count = 0;
                string[] ids = IDs.Split(',');

                count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.OutMoneyState == 0 && p.FinanceState == 1 && p.OriginState == 1 && p.SysState == 1 && ids.Contains(p.Id.ToString()), p => new OutMoneyOrdersRunnings { OutMoneyState = State, OutMoneyRemark = Remark, OutMoneyStaffID = model.Id, OutMoneyTime = DateTime.Now, OutMoneyAccountID = OutMoneyAccountID });
                if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == OutMoneyOrdersID && p.OutMoneyState == 0 && p.FinanceState == 1 && p.OriginState == 1 && p.SysState == 1) == 0)
                {
                    OMOContract.UpdateDirect(p => p.Id == OutMoneyOrdersID, p => new OutMoneyOrders { State = 6 });
                }
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "操作失败";
            }
            return JsonEx(result);
        }

        [Description("财务-出款单核算")]
        [HttpPost, AjaxOnly]
        public ActionResult OutMoneyOrdersAdjustAsync(int OutMoneyOrdersID)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var omo = OMOContract.GetByKey(OutMoneyOrdersID);
            try
            {
                OMORContract.Repository.UnitOfWork.BeginTransaction();
                var query = (from a in OMORContract.Entities
                         where a.OutMoneyOrdersID == OutMoneyOrdersID && a.FinanceState == 1 && a.OriginState == 1 && a.SysState == 1 && a.OutMoneyState == 1
                         select new 
                         {
                             Amount = a.Amount,
                             BrokerageRunningsID = a.BrokerageRunningsID,
                             CreatedTime = DateTime.Now,
                             Remark = "",
                             StaffID = model.Id,
                             Id = 0,
                             IsDeleted = false,
                             IsLocked = false
                        });
                List<BrokerageSettleAccountsRunnings> bsl = new List<BrokerageSettleAccountsRunnings>();
                foreach (var item in query.ToList())
                {
                    bsl.Add(new BrokerageSettleAccountsRunnings() { Amount = item.Amount, BrokerageRunningsID = item.BrokerageRunningsID, CreatedTime = DateTime.Now, Remark = "", StaffID = model.Id, Id = 0, IsDeleted = false, IsLocked = false });
                }
                int count = BSContract.Insert(bsl);
                if (count > 0)
                {
                    var q = from a in BRContract.Entities
                            join b in OMORContract.Entities on a.Id equals b.BrokerageRunningsID
                            where b.OutMoneyOrdersID == OutMoneyOrdersID
                            select new
                            {
                                Id = a.Id,
                                Amount = a.Amount,
                                AuditingStaffID = a.AuditingStaffID,
                                AuditingTime = a.AuditingTime,
                                BrokerageTypeID = a.BrokerageTypeID,
                                ConfirmStaffID = a.ConfirmStaffID,
                                ConfirmTime = a.ConfirmTime,
                                IsReceipt = a.IsReceipt,
                                ModuleID = a.ModuleID,
                                RunningsID = a.RunningsID,
                                Tax = a.Tax,
                                State = a.Amount - a.Tax - b.Amount - (from bs in BSContract.Entities where bs.BrokerageRunningsID == a.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == a.Id select new { a = bs.Amount }).Sum(x => x.a) == 0 ? 4 : 3,
                            };
                    foreach (var item in q.ToList())
                    {
                        BRContract.Update(new BrokerageRunnings() { Amount = item.Amount, AuditingStaffID = item.AuditingStaffID, AuditingTime = item.AuditingTime, BrokerageTypeID = item.BrokerageTypeID, ConfirmStaffID = item.ConfirmStaffID, ConfirmTime = item.ConfirmTime, Id = item.Id, IsReceipt = item.IsReceipt, ModuleID = item.ModuleID, RunningsID = item.RunningsID, State = item.State, Tax = item.Tax });
                    }
                    var o = OMOContract.GetByKey(OutMoneyOrdersID);
                    o.State = 7;
                    OMOContract.Update(o);
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
                OMORContract.Repository.UnitOfWork.Commit();

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "操作失败";
                OMORContract.Repository.UnitOfWork.Rollback();
            }
            return JsonEx(result);
        }
        [Description("财务-修改出款单出款金额")]
        [HttpPost, AjaxOnly]
        public ActionResult ModifyAmountAsync(int OutMoneyOrdersID,string IDs ,decimal Amount)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            string[] ids = IDs.Split(',');
            try
            {
                if (OMOContract.Entities.Count(p => p.Id == OutMoneyOrdersID && p.State == 1) == 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "该出款单已封单。";
                }
                else
                {
                    OMORContract.Repository.UnitOfWork.BeginTransaction();
                    foreach (var item in ids)
                    {
                        OutMoneyOrdersRunnings m = OMORContract.GetByKey(Convert.ToInt32(item));
                        if (m.OutMoneyOrdersID != OutMoneyOrdersID)
                        {
                            continue;
                        }
                        BrokerageRunnings brm = BContract.GetByKey(m.BrokerageRunningsID);
                        if (BSContract.Entities.Count(p => p.BrokerageRunningsID == brm.Id) == 0)
                        {
                            if (brm.Amount-brm.Tax - Amount < 0)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (brm.Amount - brm.Tax - BSContract.Entities.Where(p => p.BrokerageRunningsID == brm.Id).Sum(p => p.Amount) - Amount < 0)
                            {
                                continue;
                            }
                        }
                        m.Amount = Amount;
                        OMORContract.Update(m);
                    }
                    OMORContract.Repository.UnitOfWork.Commit();
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
                OMORContract.Repository.UnitOfWork.Rollback();
            }
            return JsonEx(result);
        }
        [Description("财务-删除出款单明细")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteOutMoneyOrdersRunningsAsync(int OutMoneyOrdersID, string IDs)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            string[] ids = IDs.Split(',');
            try
            {
                if (OMOContract.Entities.Count(p => p.Id == OutMoneyOrdersID && p.State == 1) == 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "该出款单已封单。";
                }
                else
                {
                    OMORContract.Repository.UnitOfWork.BeginTransaction();
                    foreach (var item in ids)
                    {
                        OutMoneyOrdersRunnings m = OMORContract.GetByKey(Convert.ToInt32(item));
                        if (m.OutMoneyOrdersID != OutMoneyOrdersID)
                        {
                            continue;
                        }
                        OMORContract.Delete(m);
                    }
                    OMORContract.Repository.UnitOfWork.Commit();
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
                OMORContract.Repository.UnitOfWork.Rollback();
            }
            return JsonEx(result);
        }

    }
}